<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\User;
use App\Models\WeixinUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class ProgramController extends Controller
{

    // 根据code 进行登陆
    public function login(Request $request){
        $code = $request->code;
        if (strlen(trim($code))<6){
            return show(201,'请提交code数据');
        }
        // 获取小程序配置

        $mini = app('wechat.mini_program');
        $wxResult = $mini->auth->session($code);
//        return $wxResult;
        if (empty($wxResult)) {
            return show(205,'获取session_key及openID异常，微信内部错误');
        } else {
            $loginFail = array_key_exists('errcode', $wxResult);
            if ($loginFail) {
//                dd($wxResult);
                // 失败了，处理错误逻辑
               return show(202,'登陆失败',[
                   'is_bind'=>false,
               ]);
            } else {
                // 保存数据，做登陆处理
                $wxResult['token'] = sha1($wxResult['openid'].$wxResult['session_key']);

                // 如果存在，即意味着这个用户已经微信登陆了，这时候判断
                $res = DB::table('weixin_users')->where('openid_mini',$wxResult['openid'])->first();
                $wxResult['openid_mini'] = $wxResult['openid'];
                unset($wxResult['openid']);
                unset($wxResult['expires_in']);
                try{
                    if ($res){
                        // weixin_user表中有数据，但是User表中的user_id没有，
                       $open_mini = $res->openid_mini;
                       if (!$open_mini){
                           $data = [
                               'openid_mini'=>$wxResult['openid_mini'],
                               'token'=>$wxResult['token'],
                               'session_key'=>$wxResult['session_key']
                           ];
                       }else{
                           $data = [
                               'token'=>$wxResult['token'],
                               'session_key'=>$wxResult['session_key']
                           ];
                       }
                        WeixinUser::where('openid_mini',$wxResult['openid_mini'])->update($data);
                        $user_id = $res->user_id;
                        if ($user_id=='0'){
                            return show(204,'请绑定手机号',[
                                'is_bind'=>false,
                                'token'=>$wxResult['token'],
                            ]);
                        }else{
                            return show(200,'登陆成功',[
                                'is_bind'=>true,
                                'token'=>$wxResult['token'],
                            ]);
                        }
                    }else{
                        // 增加用户
                        //  weixin_user表中创建一条数据，因为user_id不存在呀
                        \App\Models\WeixinUser::create($wxResult);
                        return show(204,'请绑定手机号',[
                            'is_bind'=>false,
                            'token'=>$wxResult['token']
                        ]);
                    }
                }catch (\Exception $exception){
                    dd($exception->getMessage());
                    return show(202,'登陆失败',[
                        'is_bind'=>false,
                    ]);
                }

            }
        }
    }
    // 保存小程序用户信息
    public function saveInfo(Request $request){
        $rules = [
            'city'=>'string',
            'gender'=>'required|integer|in:0,1',
            'language'=>'string',
            'country'=>'string',
            'province'=>'string',
            'nickName'=>'required|string',
            'avatarUrl'=>'required|string',
            'token'=>'required|string'
        ];
        $message = [
            'city.*'=> '城市有误',
            'gender.*'=>'性别有误',
            'language.*'=>'语音有误',
            'country.*'=>'国家名有误',
            'province.*'=>'省名有误',
            'nickName.*'=>'昵称有误',
            'avatarUrl.*'=> '头像路径有误',
            'token.*'=>'令牌有误'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }

        $token = $request->token;
        $weixin_user = WeixinUser::where('token',$token)->first();
        if ($weixin_user){
            $nickname = $weixin_user->nickname;
            $headimgurl = $weixin_user->headimgurl;
            if($nickname!='' || $headimgurl!=''){
                return show(203,'用户信息已存在请勿重复保存');
            }
        }
        $result = $weixin_user->update([
            'nickname'=>$request->nickName,
            'headimgurl'=>$request->avatarUrl,
            'city'=>$request->city,
            'sex'=>$request->gender,
            'language'=>$request->language,
            'country'=>$request->country,
            'province'=>$request->province,
        ]);
        if (!$result){
            return show(202,'用户信息保存失败');
        }
        return show(202,'用户信息保存成功');
    }
    public function send(Request $request){
        if(preg_match("/^1[345678]{1}\d{9}$/",$request->mobile)){
            //生成验证码存入缓存
            $code = rand(100000,999999);
            Cache::put($request->mobile, ['mobile'=>$request->mobile,'code'=>$code], 60);

            //发送短信
            $url="http://send.18sms.com/msg/HttpBatchSendSM?account=vd736g&pswd=dTP8X306&mobile=".$request->mobile."&msg=%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E6%98%AF%EF%BC%9A".$code."&needstatus=true&extno=";
            file_get_contents($url);
            return ["code"=>200,"info"=>"发送成功","data"=>[]];
        }else{
            return ["code"=>201,"info"=>"手机号错误","data"=>[]];

        }
    }
    public function checkUser(Request $request){
        $code =$request->code;
        $mobile = $request->mobile;
        $token = $request->token;
        $ilike =  Cache::get($mobile);
        $sessionMobile = $ilike['mobile'];
        $sessionValidateCode =  $ilike['code'];

        if (!isset($code) || !isset($mobile) || !isset($token) || strlen($token)<6){
            return show(201,'请传手机号或验证码');
        }

        if(($mobile != $sessionMobile) || ($code != $sessionValidateCode)){
            return ["code"=>10001,"info"=>"验证码错误","data"=>[]];
        }

        //验证用户是否存在
        $user = User::where('mobile',$request->mobile)->first();
        try{
            if($user){
                $user_id = $user->id;
                WeixinUser::where('token',$token)->update(compact('user_id'));
            }else{
                $res = User::create([
                    'name'=> $mobile,
                    'mobile'=>$mobile,
                    'password'=>Hash::make($code),
                ]);
                $user_id = $res->id;
                WeixinUser::where('token',$token)->update(compact('user_id'));
            }
        }catch (\Exception $e){
            return show(202,'绑定失败');
        }
        return show(200,'绑定成功');

    }
    // 获取电话
    public function getPhone(Request $request){
        $session = $request->sesseion;
        $iv = $request->iv;
        $encryptData = $request->encryptData;
        $mini = app('wechat.mini_program');
        $decryptedData = $mini->encryptor->decryptData($session, $iv, $encryptData);
        // 保存电话操作

        return show(200,'获取电话',$decryptedData);
    }

    protected function getUserId($token){
        $weixin_user = WeixinUser::where('token',$token)->first();
        if ($weixin_user){
            $user_id  = $weixin_user->user_id;
            if ($user_id != '0'){
                return $user_id;
            }
        }
        return false;

    }
}
